package com.korion.android.devicedemon.core

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.telephony.SmsMessage
import com.korion.android.devicedemon.core.SmsMessage as SmsMsg
import android.util.Log
import com.korion.android.devicedemon.ISmsDemonService
import com.korion.android.devicedemon.base.JsonUtils
import java.text.SimpleDateFormat

class SmsReceiver : BroadcastReceiver() {

    companion object {
        const val TAG = "SmsReceiver"
        const val SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"
    }


    private val time = SystemClock.currentThreadTimeMillis()

    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "onReceiver[$time]: action=${intent.action}")
        if (intent.action == SMS_RECEIVED_ACTION) {
            val pdus = intent.extras?.get("pdus") ?: return
            val map = mutableMapOf<String, SmsMsg?>()
            (pdus as Array<Object>).forEach { pdu ->
                val smsMessage = SmsMessage.createFromPdu(pdu as ByteArray)
                val from = smsMessage.displayOriginatingAddress
                var smsMsg = map[from]
                if (smsMsg == null) {
                    smsMsg = SmsMsg().apply {
                        this.from = from
                        this.timestamp = smsMessage.timestampMillis
                    }
                    map[from] = smsMsg
                }
                smsMsg.content = smsMsg.content + smsMessage.displayMessageBody
            }
            val smsList = map.values.toList()
            Log.d(TAG, "receive sms: ${smsList.toString()}")
            val intent = Intent(context, SmsDemonService::class.java)
            // peekService request the Service has running and onBind has been called,
            // otherwise it will return null
            val service = peekService(context, intent)?.let {
                ISmsDemonService.Stub.asInterface(it)
            }
            if (service == null) {
                Log.d(TAG, "can't not peek service")
            }
            service?.run {
                smsList.forEach { msg ->
                    this.onReceiveSmsMessage(JsonUtils.toJson(msg))
                }
            }
        }
    }
}